package com.ayf.payment.game.api.channel.xingyou.util;

import com.ayf.payment.game.api.utils.MD5Util;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

public final class XingYouSignUtil {

    public static String getSign(String traceId, String methodName, Map<String,String> reqParam, String key) {
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, String> entry : reqParam.entrySet()) {
            if (!"sign".equalsIgnoreCase(entry.getKey()) && StringUtils.isNotEmpty(entry.getValue())) {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String signOriginStr = sb.toString();
        signOriginStr += "key=" + key;
        LogPortal.info("{} {} 签名原文:{}",traceId,methodName,signOriginStr);
        String sign = MD5Util.strToMd5Utf8(signOriginStr);
        if (StringUtils.isEmpty(sign)) {
            return null;
        }
        sign = sign.toUpperCase();
        LogPortal.info("{} {} 实际签名:{}",traceId,methodName,sign);
        return sign;
    }

}
